//
//  ShareController.m
//  YuiKe
//
//  Created by yuike5 yuike5 on 11-10-25.
//  Copyright 2011年 yuike. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import "ShareController.h"
#import "mcf.h"
//#import "ymall.h"
#import "UIViewAdditions.h"
#import "WeiboAuthController.h"


#define TABLE_VIEWCELL_TXT   1001
#define TABLE_VIEWCELL_IMG   1002
#define TABLE_VIEWCELL_BTN   1003
#define TABLE_VIEWCELL_CPS   1009
#define TABLE_VIEWCELL_CPS_HIDE  1012
#define TABLE_VIEWCELL_SUGGESTx   1010
#define TABLE_VIEWCELL_EMOTIONx   1011
#define TABLE_VIEWCELL_ATx        1013

#define TABLE_VIEWCELL_TXT_BAK   1004


@implementation UITableViewCellforTextView
-(void)fuckTextView:(UIView*)root {
    for (UIView* view in root.subviews) {
        if ([view isKindOfClass:[UITextView class]]) {
            UITextView* tv = (UITextView*) view;
            tv.scrollEnabled = FALSE;
            [tv resignFirstResponder];
            NSRange selectedRange = tv.selectedRange;
            tv.selectedRange = selectedRange; // 这行代码很重要。
        } else {
            [self fuckTextView:view];
        }
    }
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {   
    // recursively calls -pointInside:withEvent:. point is in the receiver's coordinate system
    UIView* view = [super hitTest:point withEvent:event];
    if ([view isKindOfClass:[UITextView class]]) 
        [self fuckTextView:self];  
    [self setSelectionStyle:UITableViewCellSelectionStyleNone];
    return view;
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {   
    // default returns YES if point is in bounds
    //[self fuckTextView:self];
    return [super pointInside:point withEvent:event];
}
@end





//private
@interface ShareController()
@property (nonatomic, copy) NSString* weibo_test_backup;
@property (nonatomic, retain) IBOutlet UITableViewCell* vCell;

// Private funcs.
-(void) updateAtButtonState;
-(void) updateButtonsLayout;
-(void) updateEmotionsList;
@end




@implementation ShareController
@synthesize weibo_test_backup;
@synthesize vCell;
@synthesize weibo_hide_text_head;
@synthesize weibo_hide_text_tail;
@synthesize titleForFooterInSection;
@synthesize imageurl;

@synthesize product_title;
@synthesize product_url;
@synthesize product_summary;

-(void) setDoneDelegate:(id)delegatex sel:(SEL)sel
{
    doneDelegate = delegatex;
    doneSel = sel;
}


- (id)initWithStyle:(UITableViewStyle)style andWeiboBase:(WeiboBase*)wb
{
    self = [super initWithStyle:style];
    if (self) {
        [[NSBundle mainBundle] loadNibNamed:@"ShareController" owner:self options:nil];
        // Custom initialization
        self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"取消" 
                                                                                 style:UIBarButtonItemStyleBordered 
                                                                                target:self 
                                                                                action:@selector(cancelBarBtnPressed)] autorelease];
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"发送" 
                                                                                  style:UIBarButtonItemStyleBordered 
                                                                                 target:self 
                                                                                 action:@selector(sendBarBtnPressed)] autorelease];
        weibobase = [wb retain];
        
        
        weiboTextView = (UITextView*)[vCell viewWithTag: TABLE_VIEWCELL_TXT];
        weiboImageView = (UIImageView*)[vCell viewWithTag: TABLE_VIEWCELL_IMG];
        weiboButtonCheck = (UIButton*)[vCell viewWithTag: TABLE_VIEWCELL_BTN];
        weiboButtonSuggestx = (UIButton*)[vCell viewWithTag:TABLE_VIEWCELL_SUGGESTx];
        weiboButtonEmotionx = (UIButton*)[vCell viewWithTag:TABLE_VIEWCELL_EMOTIONx];
        weiboButtonAtx      = (UIButton*)[vCell viewWithTag:TABLE_VIEWCELL_ATx];
        weiboCpsLabelShow = (UILabel*)[vCell viewWithTag: TABLE_VIEWCELL_CPS];
        weiboCpsLabelReal = (UILabel*)[vCell viewWithTag: TABLE_VIEWCELL_CPS_HIDE];
        //vCell.accessoryView = weiboImageView;        
        
        weiboButtonCheck.frame = weiboImageView.bounds; 
        weiboButtonSuggestx.frame = weiboImageView.bounds;
        weiboButtonEmotionx.frame = weiboImageView.bounds; 
        weiboButtonAtx.frame      = weiboImageView.bounds;

        [weiboButtonCheck addTarget:self action:@selector(weiboCheckButtonPressed:) forControlEvents: UIControlEventTouchUpInside];
        [weiboButtonCheck setImage:[UIImage imageNamed:@"37x-Checkmark.png"] forState:UIControlStateNormal];
        [weiboButtonSuggestx addTarget:self action:@selector(weiboSuggestButtonPressed:) forControlEvents: UIControlEventTouchUpInside];
        [weiboButtonSuggestx setBackgroundImage:[UIImage imageNamed:@"weibo_suggest"] forState:UIControlStateNormal];
        [weiboButtonSuggestx setBackgroundImage:[UIImage imageNamed:@"weibo_suggest2"] forState:UIControlStateHighlighted];
        
        [weiboButtonEmotionx addTarget:self action:@selector(weiboEmotionButtonPressed:) forControlEvents: UIControlEventTouchUpInside];
        [weiboButtonEmotionx setBackgroundImage:[UIImage imageNamed:@"weibo_emotion"] forState:UIControlStateNormal];
        [weiboButtonEmotionx setBackgroundImage:[UIImage imageNamed:@"weibo_emotion2"] forState:UIControlStateHighlighted];
        weiboImageSelected = YES;
        
        [weiboButtonAtx setBackgroundImage:[UIImage imageNamed:@"weibo_at"] forState:UIControlStateNormal];
        [weiboButtonAtx setBackgroundImage:[UIImage imageNamed:@"weibo_at2"] forState:UIControlStateHighlighted];
        [weiboButtonAtx addTarget:self action:@selector(atBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
        
        [weiboTextView becomeFirstResponder]; 
        mWeiboAtController = [[WeiboAtController alloc] init];
        mWeiboSuggestionController = [[WeiboSuggestionController alloc] initWithStyle:UITableViewStylePlain];
        mWeiboEmotionController = [[WeiboEmotionController alloc] initWithStyle:UITableViewStylePlain];
        
        
        emotionsx = [[NSMutableArray alloc ] init];
        [self updateEmotionsList];
        
        bool_SendBarBtnPressed_forAuth = false;
    }
    return self;
}

-(void) setWeiboCpsUrlShow:(NSString*)show andReal:(NSString*)real
{
    weiboCpsLabelShow.text = show;
    weiboCpsLabelReal.text = real;
}
-(void) setWeiboText:(NSString*)text
{//
    // 多个空格变成一个空格，同时把首位的空格截掉。。。
    int len = text.length;
    while (len != 0) {
        text = [text replace:@"  " with:@" "];
        int newlen = text.length;
        if (newlen == len) {
            text = [text strip];
            //len = text.length;
            break;
        }
        len = newlen;
    }
    
// 不用截断，因为出错了，客户端会给出相应的错误码 提示。。。截断的话，有可能吧最后的 @Yuike优客 截断了，，，就悲剧了。。。。哈哈哈    
//    int maxLength = 140-20; // 因为 对于 网址，要变成 短网址后 算字数，，，，而提交失败，界面不消失，不会造成数据丢失。
//    if (text && text.length > maxLength) // 多于140个字，截断。。。
//        text = [text substringToIndex:maxLength];
    
    if (text) { // 清除换行。。。
        text = [text replace:@"\r" with:@" "];
        text = [text replace:@"\n" with:@" "];
    }
    
    [weiboTextView setText: text];
    self.weibo_test_backup = text;
}
-(void) setWeiboSuggests:(NSArray*)array_
{
    mWeiboSuggestionController.array = array_;
    [mWeiboSuggestionController setCallback:self sel:@selector(theWeiboSuggestCallback:)];
}
-(void) setWeiboImage:(UIImage*)image
{
    [weiboImageView setImage:image];
}

-(void) weiboCheckButtonPressed: (id) sender
{
    weiboImageSelected = !weiboImageSelected;
    if (weiboImageSelected) {
        [weiboButtonCheck setImage:[UIImage imageNamed:@"37x-Checkmark.png"] forState:UIControlStateNormal];
    } else {
        [weiboButtonCheck setImage:nil forState:UIControlStateNormal];
    }
}

-(void) weiboSuggestButtonPressed: (id) sender
{    
    if (!mPopoverController)
        mPopoverController = [[UIPopoverController alloc] initWithContentViewController:mWeiboSuggestionController];
    [mPopoverController setContentViewController:mWeiboSuggestionController animated:true];
    
    [mPopoverController setPopoverContentSize:CGSizeMake(240, 320)];
    CGRect temp = [weiboButtonSuggestx frameInAncestorView:self.view];
    [mPopoverController presentPopoverFromRect:temp
                                        inView:self.view 
                      permittedArrowDirections:UIPopoverArrowDirectionLeft
                                      animated:YES];
}
-(void) weiboEmotionButtonPressed:(id)sender
{
    if (!mPopoverController)
        mPopoverController = [[UIPopoverController alloc] initWithContentViewController:mWeiboEmotionController];
    [mPopoverController setContentViewController:mWeiboEmotionController animated:true];
    
    //array 
    [mWeiboEmotionController setWeibo:emotionsx callback:self sel:@selector(theWeiboEmotionCallback:)];
    
    [mPopoverController setPopoverContentSize:CGSizeMake(240, 320)];
    CGRect temp = [weiboButtonEmotionx frameInAncestorView:self.view];
    [mPopoverController presentPopoverFromRect:temp
                                        inView:self.view 
                      permittedArrowDirections:UIPopoverArrowDirectionLeft
                                      animated:YES];
}
-(void) atBtnPressed: (id) sender {    
    if (!mPopoverController)
        mPopoverController = [[UIPopoverController alloc] initWithContentViewController:mWeiboAtController];
    [mPopoverController setContentViewController:mWeiboAtController animated:true];
    
    [mPopoverController setPopoverContentSize:CGSizeMake(240, 320)];
    CGRect temp = [weiboButtonAtx frameInAncestorView:self.view];
    [mPopoverController presentPopoverFromRect:temp
                                        inView:self.view 
                      permittedArrowDirections:UIPopoverArrowDirectionLeft
                                      animated:YES];
}

-(void) theWeiboEmotionCallback: (WeiboEmotion*) e
{    
    [weiboTextView insertString:e.phrase leftSpace:true rightSpace:true];
    [mPopoverController dismissPopoverAnimated:true];
}
-(void) theWeiboAtCallback: (WeiboUserNode*)user
{
    [weiboTextView insertString:[NSString stringWithFormat:@"@%@", user.atName] leftSpace:true rightSpace:true];
    [mPopoverController dismissPopoverAnimated:true];
}


-(void) theWeiboSuggestCallback:(NSString*)str
{
   // BOOL startSpace = [str startswith:@" "];//
   // BOOL endSpace = [str endswith:@" "]; // 比如@谁，后面必须有空格
    
    str = [str replace:@"\r" with:@" "];
    str = [str replace:@"\n" with:@" "];
    while ([str rangeOfString:@"  "].length != 0) {
        str = [str replace:@"  " with:@" "];
    }
   // str = str.strip;
    [weiboTextView insertString:str leftSpace:false rightSpace:false];
    [mPopoverController dismissPopoverAnimated:true];
}


-(void) dealloc
{
    [vCell release];
    //[weiboButton release];
    //[weiboImageView release];
    //[weiboTextView release];
    //[weiboCpsLabel release];
    [weibo_test_backup release];
    
    [weibobase setDelegateNilAll];
    YRelease(weibobase)

    YRelease(HUD)
    YRelease(imageurl)
    
    YRelease(product_title)
    YRelease(product_url)
    YRelease(product_summary)
    
    YRelease(mWeiboSuggestionController)
    YRelease(mPopoverController)
    YRelease(mWeiboEmotionController)
    YRelease(mWeiboAtController)
    YRelease(emotionsx)
    
    YRelease(titleForFooterInSection)
    [super dealloc]; // array
}



-(void) cancelBarBtnPressed
{
    BOOL ktemp = weiboTextView.text.length <= 0;
    if (!ktemp && weibo_test_backup) {
        ktemp = [weiboTextView.text.strip compare:weibo_test_backup.strip] == 0;
    }
    if (ktemp) {
//        if (doneDelegate) {
//            [doneDelegate performSelector:doneSel withObject:nil afterDelay:0.5f];
//        }
        [[self parentViewController] dismissModalViewControllerAnimated:YES];
        return;
    }
    
    // 必须保证只能出现一个，否则会发生 崩溃
    UIActionSheet* sheet = [[UIActionSheet alloc] 
                            initWithTitle:nil  
                            delegate:self  
                            cancelButtonTitle:nil  
                            destructiveButtonTitle:nil  
                            otherButtonTitles:@"确认要取消", nil];
    [sheet autorelease];
    [sheet showFromBarButtonItem:self.navigationItem.leftBarButtonItem animated:YES];
    self.navigationItem.leftBarButtonItem.enabled = false;
    self.navigationItem.rightBarButtonItem.enabled = false;
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
//        if (doneDelegate) {
//            [doneDelegate performSelector:doneSel withObject:nil afterDelay:0.5f];
//        }
        [[self parentViewController] dismissModalViewControllerAnimated:YES];
    } else {
        self.navigationItem.leftBarButtonItem.enabled = true;
        self.navigationItem.rightBarButtonItem.enabled = true;
    }
}
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    self.navigationItem.leftBarButtonItem.enabled = true;
    self.navigationItem.rightBarButtonItem.enabled = true;
}


-(void) sendBarBtnPressed
{    
    bool_SendBarBtnPressed_forAuth = false;
    
    NSString* text = weiboTextView.text.strip;
    if (!text || text.length<=0) {
        [self.view makeToast: [NSString stringWithFormat:@"%@内容为空", weibobase.title]];
        return;
    }
    
    
    
    BOOL bOk = NO;
    
        
    // 重建，因为此时，有可能已经切换帐号了。
    [weibobase reloadAuthInfo]; // 这行没有效果，与梦。
        
    if (weibobase.isAuthorized) { // backup ....
        bOk = YES;
        NSString* message = [NSString stringWithFormat:@"%@ %@", // 中间加哥空格，以防不测
                             weiboTextView.text.strip, 
                             [weibobase cpsUrlTrans: (weiboCpsLabelReal.text!=nil&&weiboCpsLabelReal.text.length!=0)?weiboCpsLabelReal.text:@""] ];
            
        message = message.strip;
        weibo_hide_text_head = weibo_hide_text_head.strip;
        weibo_hide_text_tail = weibo_hide_text_tail.strip;
            
        if (weibo_hide_text_head && weibo_hide_text_head.length) {
            message = [NSString stringWithFormat:@"%@ %@", weibo_hide_text_head, message];
        }
        if (weibo_hide_text_tail && weibo_hide_text_tail.length) {
            message = [NSString stringWithFormat:@"%@ %@", message, weibo_hide_text_tail];
        }
            
            
        // 不能替换 可能把 网址里面的也 替换了。。。就悲剧了
        //[思考] http://p.yiqifa.com/c?s=fe0346af&w=432850&c=4220&i=4482&l=0&e=&t=http://www.lamiu.com/goods_6376.html?lmtrk=lmsrc%253D990%2526pid%253Dxinpinss3
        //[思考] http://p.yiqifa.com/c?s=fe0346af&w=432850&c=4220&i=4482&l=0&e=&t=http://www.lamiu.com[good]s_6376.html?lmtrk=lmsrc%253D990%2526pid%253Dxinpinss3
        /**
        // 把腾讯的表情 替换成新浪的，新浪的表情 替换成 腾讯的
        //emotionsx
        if (weibo.theSnsId == SNS_ID_SINA_WEIBO) {
            for (WeiboEmotion* emo in emotionsx) {
                message = [message replace:emo.tencPhrase with:emo.sinaPhrase];
            }
        }
//        else if (weibo.theSnsId == SNS_ID_TENC_WEIBO) {
//            for (WeiboEmotion* emo in emotionsx) {
//                message = [message replace:emo.sinaPhrase with:emo.tencPhrase];
//            }
//        }
        else {
            assert(false);
        }*/
          
        
        if (weibobase.theSnsId == SNS_ID_QQ_SHARE) {
            // share only user input...
            //[weibobase addShare:self content:weiboTextView.text.strip product:self.product imageurl:self.imageurl];
            [weibobase addShare:self content:weiboTextView.text.strip 
                         title:product_title url:product_url
                        summary:product_summary imageurl:self.imageurl];
        } else {        
            if (weiboImageSelected)
                [weibobase commit:self content:message image:weiboImageView.image];
            else
                [weibobase commit:self content:message image:nil];
        }
    }    
    
    if (bOk == NO) {
        //[self.view makeToast: @"未绑定或者选择任何微博账号"];
        WeiboAuthController* temp = [[WeiboAuthController alloc] initWithNibName:@"WeiboAuthController" bundle:nil
                                                                           weibo:weibobase.theSnsId];
        [self.navigationController pushViewController:temp animated:YES];
        bool_SendBarBtnPressed_forAuth = true;
        [temp release];
    } else {
        self.navigationItem.leftBarButtonItem.enabled = NO;
        self.navigationItem.rightBarButtonItem.enabled = NO;
        
        [HUD release ];
        HUD = nil;
        if (HUD == nil) {
            HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:HUD];
        }
        [HUD show: YES];
    }
}
-(void) commitCallback:(WeiboBase*)weibo result:(BOOL)result
{    
    if (true) {
        self.navigationItem.leftBarButtonItem.enabled = YES;
        self.navigationItem.rightBarButtonItem.enabled = YES;
        [HUD hide: YES];
    }
    if (result) {
        [self performSelector:@selector(dismissSelfx) withObject:nil afterDelay:0.8f];
    }
}
-(void) commitCallback:(WeiboBase*)weibo
{
    [self.view makeToast: [[weibo title] stringByAppendingString:@" 发送成功"]];
    [self commitCallback:weibo result:YES];
}
-(void) commitCallbackError:(WeiboBase*)weibo reason:(NSString*)reason
{
    NSString* info = [[weibo title] stringByAppendingString:@" 发送失败"];
    if (reason && reason.length!=0) {
        info = [info stringByAppendingString:@"\n"];
        info = [info stringByAppendingString:reason.strip];
    }
    [self.view makeToast:info  duration:TOAST_DRRATION_LONG];
    [self commitCallback:weibo result:NO];
}
-(void) dismissSelfx
{
    if (doneDelegate) {
        [doneDelegate performSelector:doneSel withObject:nil afterDelay:0.5f];
    }
    [[self parentViewController] dismissModalViewControllerAnimated:YES];
}




- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
    DEF_didReceiveMemoryWarning;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    if (self.title == nil) {
        self.title = @"分享";
    }
    self.tableView.scrollEnabled = FALSE;
    [YkNetWork checkNetworkAvailable:self.view];
}

-(void) updateAtButtonState {

    if (weibobase.isAuthorized) {
        [mWeiboAtController clearDataList];
        [mWeiboAtController setWeiboId:weibobase.theSnsId callback:self sel:@selector(theWeiboAtCallback:)];
        weiboButtonAtx.hidden = false;
        [self updateButtonsLayout];
    } else {
        weiboButtonAtx.hidden = true;
        [self updateButtonsLayout];
    }
}
-(void) updateEmotionsList {
    
    [emotionsx removeAllObjects];
    NSArray* es = weibobase.emotions;
    for (WeiboEmotion* emo in es) 
        [emotionsx addObject:emo];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (bool_SendBarBtnPressed_forAuth && weibobase.isAuthorized) {
        // 就不更新界面了。。。。三不管
        [self sendBarBtnPressed];
        // 这三行不运行，没有任何危害 -- 避免缓慢 和 逻辑复杂 及 多请求
        //[self.tableView reloadData];
        //[self updateAtButtonState];
        //[self updateEmotionsList];
    } else {
        [self.tableView reloadData];
        [self updateAtButtonState];
        [self updateEmotionsList];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return TRUE;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    [weibobase reloadAuthInfo];
    // Return the number of sections.
    return 2; // 只有发微博
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section == 0)
        return 1;
    return 0;
}


-(void) updateButtonsLayout {
    
    CGRect kt = weiboButtonEmotionx.frame;
    kt.origin.x += kt.size.width + 2;

    if (!weiboButtonAtx.hidden) {
        weiboButtonAtx.frame = kt;
        kt.origin.x += kt.size.width + 2;
    }
    if (!weiboButtonSuggestx.hidden) {
        weiboButtonSuggestx.frame = kt;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = nil;//[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    int section = indexPath.section;
    //int row = indexPath.row;
    if (section == 0) {
        
        cell = self.vCell;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; // 必须，否则text view 可能丢失指针。
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.frame = [tableView rectForRowAtIndexPath:indexPath];
        
        CGRect frame = [tableView rectForRowAtIndexPath: indexPath];
        //CGPoint point = frame.origin;
        CGSize size = frame.size;
        //int width = size.width;
        int height = size.height;
        const int border = 5;
        
        CGRect temp = weiboImageView.frame;
        temp.origin = CGPointMake(0, 0);
        temp.size = CGSizeMake(height-border*2, height-border*2);
        weiboImageView.frame = temp;        
        
        //width = cell.contentView.bounds.size.width;
        int width = 480;
        int cpsHeight = 0;// 24;
        int picwidth = weiboImageView.frame.size.width;
        weiboTextView.frame = CGRectMake(border, 
                                         border,
                                         width -border - border - picwidth - border, 
                                         height -border - border  - 1 - cpsHeight);
        weiboImageView.frame = CGRectMake(width - border - picwidth, 
                                          border,
                                          picwidth, 
                                          height -border - border  - 1 - cpsHeight);
        
        {
            CGRect kt = CGRectMake(border, border, width-border*2, height-border*2);
            CGSize imageSize = [UIImage imageNamed:@"weibo_at"].size;

            kt.origin.y += kt.size.height - imageSize.height - cpsHeight;
            kt.size = imageSize;
            
            weiboButtonEmotionx.frame = kt;
            weiboButtonSuggestx.hidden = !mWeiboSuggestionController.needDisplay;
            [self updateButtonsLayout];
        }
        

        CGRect rect = CGRectMake((weiboImageView.frame.origin.x + 100.0f) ,
                                 (weiboImageView.frame.origin.y + 100.0f), 48.0f, 48.0f);
        weiboButtonCheck.frame = rect; //weiboImageView.bounds;
        
        

        weiboButtonCheck.backgroundColor = [UIColor clearColor];
//        temp = weiboImageView.frame;
//        weiboButton.frame = temp;
        
        weiboCpsLabelShow.frame = CGRectMake(weiboTextView.left, weiboTextView.bottom, width-2*border, cpsHeight);
        
        
        if (weiboImageView.image == nil) {
            weiboButtonCheck.hidden = YES;
            weiboImageView.hidden = YES;
            weiboTextView.frame = CGRectMake(border, border, width-2*border-1/*这里多个1,根据肉眼观察得结果*/, height-2*border-1 - cpsHeight);
        } else {
            weiboButtonCheck.hidden = NO;
            weiboImageView.hidden = NO;
            
            float lastWidth = weiboImageView.frame.size.width;
            weiboImageView.frame = [UIView autoAdjustRect:weiboImageView.frame toSize:weiboImageView.image.size];
            float curWidth = weiboImageView.frame.size.width;
            
            
            if (curWidth + 10 < lastWidth) { // 10个橡树，避免他们 相接....
                float xpxx = lastWidth - curWidth - 10;
                
                CGRect temp = weiboTextView.frame;
                temp.size.width += xpxx;
                weiboTextView.frame = temp;
                
                temp = weiboImageView.frame;
                temp.origin.x += xpxx / 2;
                weiboImageView.frame = temp;
            }
        }
        
        // 如果 cps url 没有，此时 把，表情 按钮下移 对齐。
        if (weiboCpsLabelShow.text==nil ||weiboCpsLabelShow.text.length<=0) {
            weiboButtonSuggestx.bottom = weiboCpsLabelShow.bottom;
            weiboButtonEmotionx.bottom = weiboCpsLabelShow.bottom;
            weiboButtonAtx.bottom = weiboCpsLabelShow.bottom;
        }
        
        
        // 设置背景
        UIView* textv = [vCell viewWithTag:TABLE_VIEWCELL_TXT];
        UIView* textf = [vCell viewWithTag:TABLE_VIEWCELL_TXT_BAK];
        temp = textv.frame;
        temp.size.height += 3; // 貌似多3个橡树 才 对齐了。的。。。
        textf.frame = temp;
        textf.hidden = true;
    }
    
    if (weibobase.theSnsId == SNS_ID_QQ_SHARE) {
        // QQ share 特殊处理
        weiboButtonSuggestx.frame = weiboButtonEmotionx.frame;
        weiboButtonEmotionx.hidden = true;
        weiboButtonAtx.hidden = true;
    }
    weiboButtonCheck.hidden = true;
    return cell;
}

-(void) switchAction: (id) sender {
    [self updateAtButtonState];
    [self updateEmotionsList];
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    int section = indexPath.section;
    //int row = indexPath.row;
    if (section == 0) {
        return 240;
    }
    return 50;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    if (section == 0)
        return titleForFooterInSection;
    if (section == 1) {
        if (weibobase.theSnsId == SNS_ID_QQ_SHARE)
            return @"同步分享到QQ空间、朋友网、腾讯微博";
    }
    return nil;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"Nib name" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
//    int section = indexPath.section;
    //int row = indexPath.row;
//    if ((array_authed.count != 0 && section == 2) || (array_authed.count == 0 && section == 1)) {
//        ShareAccountMgrController* temp = [[ShareAccountMgrController alloc] initWithStyle:UITableViewStylePlain];
//        [self.navigationController pushViewController:temp animated:YES];
//        [temp autorelease];
//    }
}

@end
